
from fileinput import filename
from genericpath import isdir, isfile
import subprocess,os,datetime
def callRemoteCommand(passwd,command):
    expectStr = """
    set timeout 10
    spawn {command2}
    expect "password:" {send "{passwd}\r"}
    interact
    """
    with open("./expect.sh", 'w+',encoding='utf-8') as f:
        f.write(expectStr.replace("{command2}",command).replace("{passwd}",passwd))
    print(subprocess.call("expect ./expect.sh",shell=True))

def remoteCommand(serverInfo={},thenCommand=""):
    callRemoteCommand(passwd=serverInfo["passwd"].replace("$","\$"),command="ssh -p "+serverInfo["port"]+" "+serverInfo["user"]+f" \"{thenCommand}\"")
def uploadFileWithScp(filePath,isDir,tempDir="",serverInfo={},serverInfo2={}):
    fileName = filePath.split("/")[-1]
    otherPara = "-r " if isDir else ""
    if "user" not in serverInfo:
        print("请输入服务器信息")
        return
    if len(filePath) > 0:
        callRemoteCommand(passwd=serverInfo["passwd"].replace("$","\$"),command="scp -P "+serverInfo["port"]+f" {otherPara}{filePath} "+serverInfo["user"]+f":~{tempDir}/")

        if "user" in serverInfo2:
            command3 = "scp -P "+serverInfo2["port"]+f" {otherPara} .{tempDir}/{fileName} "+serverInfo2["user"]+":~/"
            command2 = "ssh -p "+serverInfo["port"]+" "+serverInfo["user"]+f" \"{command3}\""
            callRemoteCommand(passwd=serverInfo["passwd"].replace("$","\$"),command=command2)
# if __name__ ==  "__main__":
#     # uploadFileWithScp(filePath = "/Users/wangshuguan/Desktop/3x",isDir=True,tempDir="/wsg",serverInfo={"user":"root@36.133.43.107","passwd":"JZzx@2022#","port":"2200"},serverInfo2={"user":"root@192.168.0.29","passwd":"JZzx@2022#","port":"22"})
#     import subprocess
 
#     s = subprocess.Popen("/usr/bin/ssh -p 2200 root@root@36.133.43.107", stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=True)
#     s.stdin.write(b"JZzx@2022#\n")
#     s.stdin.close()
    
#     out = s.stdout.read().decode("GBK")
#     s.stdout.close()
#     print(out)

import paramiko
import sys

hostname = "192.168.0.29"  # 业务主机ip
username = "root"
password = "JZzx@2022#"


port = 22
passinfo = 'password: '  # 登陆输入密码时的前缀
def upload2(local_dir,remote_dir,sftp):
    for root,dirs,files in os.walk(local_dir):
        for filespath in files:
            if filespath != ".DS_Store":
                local_file = os.path.join(root,filespath)
                a = local_file.replace(local_dir,'')
                remote_file = os.path.join(remote_dir,a)
                try:
                    sftp.put(local_file,remote_file)
                except Exception as e:
                    sftp.mkdir(os.path.split(remote_file)[0])
                    sftp.put(local_file,remote_file)
                print (f"upload {local_file} to remote {remote_file}")
        for name in dirs:
            local_path = os.path.join(root,name)
            a = local_path.replace(local_dir,'')
            remote_path = os.path.join(remote_dir,a)
            try:
                sftp.mkdir(remote_path)
                print (f"mkdir path {remote_path}")
            except Exception as e:
                print (e)
def init():
    paramiko.util.log_to_file('syslogin.log')   # 将信息放到日志中
def deinit(ssh):
    ssh.close() 
def connect(info):
    users = info["user"].split("@")
    blip = users[1]  # 堡垒机ip
    bluser = users[0]
    blpasswd = info["passwd"]
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=blip,port=info["port"], username=bluser, password=blpasswd)  # 堡垒机连接
    return ssh

def upload(ssh,localFile,remoteDir="/root/"):
    fileName = localFile.split("/")[-1]
    tran = ssh.get_transport()
    sftp = paramiko.SFTPClient.from_transport(tran)
    print ('upload file start %s ' % datetime.datetime.now())
    if os.path.isdir(localFile):
        upload2(local_dir=localFile,remote_dir=remoteDir,sftp=sftp)
    else:
        sftp.put(localFile,remoteDir+fileName)
        print (f"upload {localFile} to remote {remoteDir+fileName}")
    print (f"upload file success {datetime.datetime.now()}")
def uploadSecondServer(ssh,localFile,info):
    users = info["user"].split("@")
    hostname = users[1]
    username = users[0]
    port = info["port"]
    password = info["passwd"]
    channel = ssh.invoke_shell()
    pama = ""
    if os.path.isdir(localFile):
        pama = '-r '
    buff = ''
    resp = ''
    channel.sendall('scp -P '+f"{port} "+pama+localFile+' '+username+'@'+hostname+':~/\n')
    if len(password) > 0:
        while not buff.endswith(passinfo):  # 是否以字符串 'password 结尾
            try:
                resp = channel.recv(9999)  #
                print(resp)
            except Exception as e:
                print('Error info:%s 连接超时.' % (str(e)))
                channel.close()
            buff = resp.decode()   # 获取的resp是bytes类型，测试的时候一直报错，最后才发现这个原因
            if not buff.find('yes/no') == -1:  # 模拟登陆是输入yes
                channel.sendall('yes\n')
                buff = ''
        channel.send(password + '\n')  # 发送密码

    buff = ''
    while not buff.endswith('# '):
        resp = channel.recv(9999)
        if not resp.decode().find(passinfo) == -1:
            print('Error info: 认证失败.')
            channel.close()
        buff += resp.decode()

        
    channel.send('ls -l\n')  # 发送密码
    buff = ''
    try:
        while buff.find('# ') == -1:
            resp = channel.recv(9999)
            buff += resp.decode()
    except Exception as e:
        print("错误:" + str(e))
    print(buff)
    channel.close()


def processYewuSite(ssh):
    # new session
    channel = ssh.invoke_shell()
    channel.settimeout(20)

    buff = ''
    resp = ''
    channel.sendall('ssh -p '+f"{port}"+' '+username+'@'+hostname+'\n')  # 发送ssh root@192.168.5.45
    while not buff.endswith(passinfo):  # 是否以字符串 'password 结尾
        try:
            resp = channel.recv(9999)  #
            print(resp)
        except Exception as e:
            print('Error info:%s 连接超时.' % (str(e)))
            channel.close()
            ssh.close()
            sys.exit()
        buff += resp.decode()   # 获取的resp是bytes类型，测试的时候一直报错，最后才发现这个原因
        if not buff.find('yes/no') == -1:  # 模拟登陆是输入yes
            channel.sendall('yes\n')
            buff = ''
    channel.send(password + '\n')  # 发送密码

    buff = ''
    while not buff.endswith('# '):
        resp = channel.recv(9999)
        if not resp.decode().find(passinfo) == -1:
            print('Error info: 认证失败.')
            channel.close()
            ssh.close()
            sys.exit()
        buff += resp.decode()

    # 通过循环实现连续输入
    # while True:
    #     ml = input('请输入命令:')


    channel.sendall("ls -l" + '\n')  # 发送测试命令
    buff = ''
    try:
        while buff.find('# ') == -1:
            resp = channel.recv(9999)
            buff += resp.decode()
    except Exception as e:
        print("错误:" + str(e))
    print(buff)
def uploadFiles():
    init()
    with open("./政协/server.csv") as f:
        for x in f.readlines():
            str = x.strip()
            if len(str) > 0 and not str.startswith("#"):
                arr = str.split(",")
                ssh = connect({"user":arr[3],"passwd":arr[5],"port":arr[4]})
                upload(ssh,localFile="/Users/wangshuguan/Documents/20221008/zhengxie-admin.jar",remoteDir="/root/")
                deinit(ssh)
                print(f"{arr[1]}结束")
if __name__ == "__main__":
    uploadFiles()
    # print("aa")






# channel.close()